import {Component, Inject, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {GnMessageService, GnTable} from "geminis-ng";
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";
import {GnTableColumn} from "geminis-ng/data/table.component";

@Component({
  selector: 'gn-manage-role-func',
  templateUrl: './role-func.component.html'
})
export class RoleFuncComponent extends GnTable implements OnInit {

  columns: GnTableColumn[] = [
    {label: '功能', field: 'name'}
  ];

  private roleFuncLoaded = false;

  constructor(private httpClient: HttpClient,
              private messageService: GnMessageService,
              private dialog: MatDialogRef<void>,
              @Inject(MAT_DIALOG_DATA) private roleId: string) {
    super();
  }

  confirm(): void {
    this.httpClient.put('/MANAGE-SERVICE/roles/' + this.roleId + '/function', this.table.selectedIds)
      .subscribe(() => {
        this.messageService.success('角色授权已保存');
        this.dialog.close("confirmed");
      }, error => {
        this.messageService.error({message: '保存角色授权错误', error: error.error});
      });
  }

  ngOnInit(): void {

    this.table.loaded.subscribe(() => {
      if (this.roleFuncLoaded) {
        return;
      }
      const pageInfo = {
        'pageIndex': 0,
        'pageSize': 1,
        'filterGroup': {filters: [{'field': 'id', 'compareType': '=', 'value': this.roleId}]},
        'includes': ['functions']
      };

      this.httpClient.post('/MANAGE-SERVICE/roles', pageInfo)
        .subscribe((role: any) => {
          this.table.selectIds(role.content[0].functions.map(func => func.id));
          this.roleFuncLoaded = true;
        }, error => {
          this.messageService.error({message: '获取角色信息错误', error: error.error});
        });
    });

  }

}
